package com.i1314i.reportsystem.controller.publics;

import com.i1314i.reportsystem.po.CommonMsg;
import com.i1314i.reportsystem.po.ResultMap;
import com.i1314i.reportsystem.po.User;
import com.i1314i.reportsystem.service.user.UserService;
import com.i1314i.reportsystem.shiro.exception.UserException;
import com.i1314i.reportsystem.utils.inimsg.UserMsgUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author 平行时空
 * @created 2018-09-18 21:02
 **/
@RestController
@RequestMapping(value = "/public")
public class LoginController {
    @Autowired
    private  ResultMap resultMap;
    @Autowired
    private UserService userService;


    /**
     * 用户登录
     * @param user
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultMap login(@RequestBody User user) throws IOException {
        try {
            checkUser(user);
        } catch (UserException e) {
            resultMap
                    .code("100")
                    .msg(e.getMessage());
            return resultMap;
        }
        return userService.login(user);
    }


    /**
     * 登陆校验
     * @param user
     * @return
     * @throws UserException
     */
    public boolean checkUser(User user) throws UserException {
        if(StringUtils.isEmpty(user.getUsername())){
            throw new UserException(UserMsgUtils.login_username_is_null_msg);
        }else if(StringUtils.isEmpty(user.getPassword())){
            throw new UserException(UserMsgUtils.login_password_is_null_msg);
        }else  if (StringUtils.isEmpty(user.getCode())){
            throw new UserException(UserMsgUtils.login_code_is_null_msg);
        }
        return true;
    }
}
